package self.realm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by hasee on 2018/1/29.
 */
public class UserDao {

    public User getUserWithName(Connection conn,String userName){


        User user = null ;

        String sql = "select * from t_user where userName = ?" ;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,userName);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("userName"));
                user.setPassword(rs.getString("password"));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return user ;

    }

    public Set<String> getRolesWithName(Connection conn, String userName) {

        Set<String> roles = new HashSet<>();

        String sql = "select * from t_user u,t_role r where u.roleId = r.id and u.userName = ?" ;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,userName);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                roles.add(rs.getString("roleName"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return roles ;

    }

    public Set<String> getPermissionsWithName(Connection conn, String userName) {

        Set<String> perms = new HashSet<>();

        String sql = "select * from t_user u ,t_role r,t_permission p where u.roleId = r.id and p.roleId = r.id and u.userName=?" ;

        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,userName);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                perms.add(rs.getString("permissionName"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return perms;
    }
}
